//
//  NotificationPushHelper.m
//  koolearnMotion
//
//  Created by 崔宝印 on 2017/5/22.
//  Copyright © 2017年 koolearn. All rights reserved.
//

#import "KooAPNSManager.h"
#import <CloudPushSDK/CloudPushSDK.h>
#import <UserNotifications/UserNotifications.h>
#import "KooTimeTool.h"
#import "KooThirdMacro.h"
#import "KooAPNSModel.h"
#import <CTMediator+KooDaYi.h>
#import <CTMediator+KooProductDetail.h>

NSString * const kLocalNotificationProductId = @"localPId";
NSString * const kLocalNotificationUnitId = @"localUId";
NSString * const kLocalNotificationTag = @"localTag";

static BOOL needJumpApns;
static NSDictionary *apnsUserInfo;

@interface KooAPNSManager ()<UNUserNotificationCenterDelegate>

@end

@implementation KooAPNSManager

+ (void)initAliPushWith:(UIApplication *)application options:(NSDictionary *)launchOptions
{
    [KooAPNSManager apnsRegisterStart:application];
    [KooAPNSManager aliPushRegisterStart];
    [CloudPushSDK sendNotificationAck:launchOptions];
    [KooAPNSManager handleNotificationOpenApp:launchOptions];
}

#pragma mark - start APNS register
+ (void)apnsRegisterStart:(UIApplication *)application
{
    if (@available(iOS 10.0, *))
    {
        [KooAPNSManager apnsRegisterStartFor10Bigger:application];
    }
    else
    {
        [KooAPNSManager apnsRegisterStartFor10Smaller:application];
    }
}

+ (void)apnsRegisterStartFor10Bigger:(UIApplication *)application
{
    UNUserNotificationCenter *notificationCenter = [UNUserNotificationCenter currentNotificationCenter];
    notificationCenter.delegate = [KooAPNSManager class];
    // 请求推送权限
    [notificationCenter requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionBadge | UNAuthorizationOptionSound completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) // 授权成功，向APNs注册，获取deviceToken
        {
            NSLog(@"User authored notification.");
            dispatch_async(dispatch_get_main_queue(), ^{
                [application registerForRemoteNotifications];
            });
        }
        else//授权失败
        {
            NSLog(@"User denied notification.");
        }
    }];
}

+ (void)apnsRegisterStartFor10Smaller:(UIApplication *)application
{
    [application registerUserNotificationSettings:
     [UIUserNotificationSettings settingsForTypes:
      (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge)
                                       categories:nil]];
    [application registerForRemoteNotifications];
}

#pragma mark - start AliPush register
+ (void)aliPushRegisterStart
{
    // SDK初始化
    [CloudPushSDK asyncInit:KooAliPushAPPKey appSecret:KooAliPushAPPSecret callback:^(CloudPushCallbackResult *res) {
        if (res.success)
        {
            NSLog(@"Push SDK init success, deviceId: %@.", [CloudPushSDK getDeviceId]);
        }
        else
        {
            NSLog(@"Push SDK init failed, error: %@", res.error);
        }
    }];
}

#pragma mark - APNS Register CallBack
+ (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [KooAPNSManager apnsRegisterSuccessWithDeviceToken:deviceToken];
}

+ (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [KooAPNSManager apnsRegisterFailedWithError:error];
}

#pragma mark - Handle APNS register callback
+ (void)apnsRegisterSuccessWithDeviceToken:(NSData *)deviceToken
{
    [CloudPushSDK registerDevice:deviceToken withCallback:^(CloudPushCallbackResult *res) {
        if (res.success)
        {
            NSLog(@"Register deviceToken success, deviceToken: %@", [CloudPushSDK getApnsDeviceToken]);
        }
        else
        {
            NSLog(@"Register deviceToken failed, error: %@", res.error);
        }
    }];
}

+ (void)apnsRegisterFailedWithError:(NSError *)error
{
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError %@", error);
}

#pragma mark - iOS9 ReceiveRemoteNotification
/**
 iOS 10以下收到通知
 1：App激活时收到通知
 2：App后台运行，点通知激活App
 */
+ (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    //App后台运行，点击远程推送启动App
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive)
    {
        [KooAPNSManager handleRemoteNotification:userInfo activeApp:YES];
    }
    //App前台运行，收到远程推送
    else if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive)
    {
        [KooAPNSManager handleRemoteNotification:userInfo activeApp:NO];
    }
}

#pragma mark - iOS10+ ReceiveRemoteNotification
/**
  iOS 10以上收到通知
 1：App激活时收到通知
 */
+ (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler
{
    completionHandler(UNNotificationPresentationOptionNone);
    [KooAPNSManager handleRemoteNotification:notification.request.content.userInfo activeApp:NO];
}

/**
 iOS 10以上收到通知
 1：App后台运行，点击推送激活App
 2：App被杀死，点击推送启动App
 */
+ (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)(void))completionHandler
{
    NSString *userAction = response.actionIdentifier;
    UNNotificationContent *content = response.notification.request.content;
    NSDictionary *userDic = content.userInfo;
    if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier])
    {
        if (userDic != nil && [[userDic allKeys] containsObject:kLocalNotificationTag])//本地通知
        {
        }
        else if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]])
        {
            [KooAPNSManager handleRemoteNotification:userDic activeApp:YES];
        }
    }
    completionHandler();
}

/**
 处理iOS10以下 点击通知打开APP
 */
+ (void)handleNotificationOpenApp:(NSDictionary *)launchOptions
{
    if (!launchOptions) return;
    if (![launchOptions.allKeys containsObject:UIApplicationLaunchOptionsRemoteNotificationKey] &&
        ![launchOptions.allKeys containsObject:UIApplicationLaunchOptionsLocalNotificationKey])
        return;
    
    NSDictionary *remoteDic = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    UILocalNotification *localNotif =[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (remoteDic)
    {
        [KooAPNSManager handleRemoteNotification:remoteDic activeApp:YES];
    }
    if (localNotif)
    {
        
    }
}

#pragma mark - Methods
/**
 检查是否需要跳转
 原因：当UIWindow的rootcontroller不是UItabviewController时，存储跳转，等UItabviewController加载完时检测
 */
+ (void)checkNeedJumpApns
{
    if (needJumpApns)
    {
        [KooAPNSManager handleRemoteJumpWithUserInfo:apnsUserInfo];
    }
}

#pragma mark - NotficationHandler
/**
 处理收到的远程推送
 @param content 推送内容
 @param active 是否通过点击推送 启动/激活了APP
 */
+ (void)handleRemoteNotification:(NSDictionary *)userInfo activeApp:(BOOL)active
{
    if (active && userInfo)//跳转
    {
        [KooAPNSManager handleRemoteJumpWithUserInfo:userInfo];
    }
}

+ (void)handleRemoteJumpWithUserInfo:(NSDictionary *)userInfo
{
    if (!userInfo) return;
    
    KooAPNSModel *model = [KooAPNSModel mj_objectWithKeyValues:userInfo];

    if (model.nim)//跳转IM消息列表
    {
        [KooAPNSManager apnsIMJumpWithUserInfo:userInfo];
    }
    else if (model.imNoticeType == 2)//跳转答疑
    {
        [[CTMediator sharedInstance] daYi_openDetailWithQuestionId:model.questionId completeHandle:^(UIViewController *detailViewController, NSError *error) {
            [KooAPNSManager apnsVCJumpWithController:detailViewController userInfo:userInfo];
        }];
    }
    else if (model.imNoticeType == 1)//跳转直播
    {
        UIViewController *controller = [[CTMediator sharedInstance] CTMediator_OpenProductDetailVCWithUserProductId:model.userProductId OrderNo:model.orderNo ProductId:model.productId ProductLine:model.productLine SeasonCode:model.seasonCode SeasonId:model.seasonId IsCatalogCourse:model.isCatalogCourse];
        [KooAPNSManager apnsVCJumpWithController:controller userInfo:userInfo];
    }
}

+ (void)apnsIMJumpWithUserInfo:(NSDictionary *)userInfo
{
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([rootVC isKindOfClass:[UITabBarController class]])
    {
        UITabBarController *tab = (UITabBarController *)rootVC;
        [tab setSelectedIndex:2];
        needJumpApns = NO;
        apnsUserInfo = nil;
    }
    else
    {
        needJumpApns = YES;
        apnsUserInfo = userInfo;
    }
}

+ (void)apnsVCJumpWithController:(UIViewController *)controller userInfo:(NSDictionary *)userInfo
{
    if (!controller) return;
    
    UIViewController *rootVC = [UIApplication sharedApplication].keyWindow.rootViewController;
    if ([rootVC isKindOfClass:[UITabBarController class]])
    {
        needJumpApns = NO;
        apnsUserInfo = nil;
        
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:controller];
        [rootVC presentViewController:nav animated:YES completion:nil];
    }
    else
    {
        needJumpApns = YES;
        apnsUserInfo = userInfo;
    }
}

#pragma mark - APNS bind/unbind Users
+ (void)refreshLoginUserId:(NSString *)userId
{
    if (!userId)
    {
        [CloudPushSDK unbindAccount:^(CloudPushCallbackResult *res) {
            if (res.success)
            {
                NSLog(@"阿里云推送账户解绑成功");
            }
            else
            {
                NSLog(@"阿里云推送账户解绑失败:%@", [res.error localizedDescription]);
            }
        }];
    }
    else
    {
        [CloudPushSDK bindAccount:userId withCallback:^(CloudPushCallbackResult *res) {
            if (res.success)
            {
                NSLog(@"阿里云推送账户绑定成功:%@",userId);
            }
            else
            {
                NSLog(@"阿里云推送账户绑定失败:%@", [res.error localizedDescription]);
            }
        }];
    }
}

#pragma mark - Local Notification
///**
// 排序本地通知
// */
//+ (void)sortLocalNotification
//{
//    dispatch_async(dispatch_get_global_queue(0, 0), ^{
//        NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
//        [notifications sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
//            UILocalNotification *notification1 = obj1;
//            UILocalNotification *notification2 = obj2;
//            return [notification1.fireDate compare:notification2.fireDate];
//        }];
//        
//        [[UIApplication sharedApplication] cancelAllLocalNotifications];
//        for (UILocalNotification *notification in notifications)
//        {
//            notification.applicationIconBadgeNumber = [notifications indexOfObject:notification] + 1;
//            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
//        }
//    });
//}

+ (void)addLoacalNotificationWithStartTime:(NSString *)startTime
                               teacherName:(NSString *)teacherName
                                  liveName:(NSString *)productName
                                    liveId:(NSString *)liveId
{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UILocalNotification *notification = [[UILocalNotification alloc] init];
        notification.timeZone = [NSTimeZone defaultTimeZone];
        notification.repeatInterval = 0;
        notification.applicationIconBadgeNumber = 1;
        notification.soundName = UILocalNotificationDefaultSoundName;
        NSString *notificationTag = [NSString stringWithFormat:@"%@-%@",liveId,startTime];
        notification.category = notificationTag;
        
        NSDate *fireDate = [NSDate dateWithTimeInterval:-300 sinceDate:[KooTimeTool getLocalFromTimeSp:startTime]];
        NSString *alertBody = [NSString stringWithFormat:@"%@老师主讲的%@将于5分钟后开始直播",teacherName, productName];
        notification.fireDate = fireDate;
        notification.alertBody = alertBody;
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"category == %@",notificationTag];
        NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
        NSArray *results = [notifications filteredArrayUsingPredicate:predicate];
        if (!results.count) {
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)])
            {
                UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
                UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                         categories:nil];
                [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
            }
            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
        }
    });
}


@end
